//学习的tab页面

import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:hktk_app/dao/home_dao.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/live_dao.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/dao/package_dao.dart';
import 'package:hktk_app/dialog/buy_dialog.dart';
import 'package:hktk_app/ienum/home/column_position_enum.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/industry/category_model.dart';
import 'package:hktk_app/model/my/app_list_model.dart';
import 'package:hktk_app/model/package/package_model.dart';
import 'package:hktk_app/painter/triangle_painter.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/screen_adapter_helper.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:table_calendar/table_calendar.dart';

class StudyPage extends StatefulWidget {
  final int initTabIndex;

  const StudyPage({super.key, this.initTabIndex = 0});

  @override
  State<StudyPage> createState() => StudyPageState();
}

class StudyPageState extends State<StudyPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  GlobalKey iconKey = GlobalKey();
  CalendarFormat _calendarFormat = CalendarFormat.month;
  late DateTime now;
  late TabController tabController;
  late bool _loading = false;
  late bool _loading1 = false;
  late bool _loading2 = false;
  late List<Map<String, dynamic>> _list1 = [
    {
      "text": "听课记录",
      "pageName": "/video-records",
      "icon": "images/study/icon1.svg"
    },
    {
      "text": "离线课程",
      "pageName": "/save-video-list",
      "icon": "images/study/icon2.svg"
    },
    {
      "text": "考试日历",
      "pageName": "/mine/calendar",
      "icon": "images/study/icon3.svg"
    },
    {"text": "课程笔记", "pageName": "/my-note", "icon": "images/study/icon4.svg"},
    {
      "text": "讲义下载",
      "pageName": "/mine/download",
      "icon": "images/study/icon5.svg"
    },
  ];

  // 根据考试获取的科目
  late Future<List<CategoryModel>?> _categoryList;
  late Future<dynamic>? _columnList;
  late int? _selectedCategoryId;
  late String? _selectedColumnId;
  late List<ColumnModel>? _columnList1 = [];
  late List<dynamic> data0 = [];
  late List<dynamic> data1 = [];
  late List<dynamic> liveList = [];
  late List<AppListModel> questionList = [];

  late int _selectedTabIndex = 0;
  final typeMap = {
    0: [5],
    2: [1, 2, 3, 4],
  };

  @override
  void initState() {
    //   initState
    super.initState();
    _selectedTabIndex = widget.initTabIndex;
    tabController =
        TabController(length: 3, vsync: this, initialIndex: _selectedTabIndex);
    now = DateTime.now();

    // _categoryList =
    //     IndustryDao.leafList(examId: IndustryDao.getExamKey().examId);
    //
    // _categoryList.then((res) {
    //   if (res != null && res.isNotEmpty) {
    //     _selectedCategoryId = res![0].id;
    //     _columnList = HomeDao.columnByCategory(
    //         categoryId: res![0].id!,
    //         groupId: 6,
    //         columnEnum: ColumnPositionEnum.jgqy);
    //     _columnList!.then((res) {
    //       if (res != null && res.isNotEmpty) {
    //         _selectedColumnId = res![0].id!;
    //         _columnList1  = res;
    //       }
    //     });
    //   }
    // });

    //   初始化获取当前科目栏目，默认选中第一项，跟据选中项初始化获取第一个tab(课程，包括推荐课程，已购课程)
    //   切换tab时，重新获取栏目，重新获取tab内容

    // 期望所以的初始请求数据获取完成再渲染页面，也期望跳转页面后，所有未完成的请求释放资源

    _loading = true;
    Future.wait([
      PackageDao.listWithColumnType({
        "examId": IndustryDao.getExamKey().examId,
        "types": typeMap[_selectedTabIndex]!.join(","),
        "buying": "false"
      }).then((res) {
        data0 = res as List<dynamic>;
      }).catchError((e) {}),
      PackageDao.listWithColumnType({
        "examId": IndustryDao.getExamKey().examId,
        "types": typeMap[_selectedTabIndex]!.join(","),
        "buying": "true"
      }).then((res) {
        data1 = res as List<dynamic>;
      }),
      LiveDao.getVideoList(1, 100).then((res) {
        liveList = (res as Map<String, dynamic>)["records"];
      }),
      MyDao.appList().then((res) {
        questionList = res;
      })
    ]).then((res) {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }).catchError((error) {
      if (mounted) {
        _loading = false;
        ToastUtil.show(context: context, msg: "未知错误");
        setState(() {});
      }
    });

    //   获取预约的直播
  }

  @override
  void dispose() {
    //   dispose
    super.dispose();
    tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SafeArea(
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.only(left: 16, right: 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, "/select-exam");
                    //   DropdownButton
                  },
                  child: Row(
                    children: [
                      Text(
                        IndustryDao.getExamKey().examName,
                        style: FontUtil.fontBlack1(16,
                            fontWeight: FontWeight.w500),
                      ),
                      hiSpace(width: 8),
                      CustomPaint(
                        painter: TrianglePainter(),
                      )
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,
                        constraints: BoxConstraints(
                            maxHeight: ScreenUtil().screenHeight * 0.8),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(24),
                            topRight: Radius.circular(24),
                          ),
                        ),
                        builder: (BuildContext context) {
                          return Container(
                            height: 100,
                            padding: EdgeInsets.only(top: 10, bottom: 10),
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                for (var item in _list1)
                                  GestureDetector(
                                    onTap: () {
                                      //   点击跳转
                                      if (item["pageName"] != null) {
                                        Navigator.pushNamed(
                                            context, item["pageName"]);
                                      }
                                    },
                                    child: Column(
                                      spacing: 5,
                                      children: [
                                        Container(
                                          padding: EdgeInsets.all(10),
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(24)),
                                              color: Color(0xFFF4FAFF)),
                                          child: SvgPicture.asset(
                                            item["icon"],
                                            width: 28,
                                            height: 28,
                                          ),
                                        ),
                                        Text(
                                          item["text"] as String,
                                          style: TextStyle(fontSize: 14),
                                        )
                                      ],
                                    ),
                                  )
                              ],
                            ),
                          );
                        });
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Image.asset(
                        "images/tab/tool1.png",
                        width: 24,
                        height: 24,
                      ),
                      Text(
                        "学习工具",
                        style: TextStyle(fontSize: 10),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
          Container(
            height: 48,
            child: TabBar(
              tabAlignment: TabAlignment.fill,
              labelColor: Colors.black,
              dividerHeight: 0,
              indicator: GradientUnderlineTabIndicator(
                colors: [Color(0xFF3C6CFF), Color(0xFFE5EBFF)], // 渐变色
                lineHeight: 3.0, // 下划线高度
                // borderRadius: BorderRadius.circular(22.0.w), // 圆角
              ),
              // indicator: UnderlineTabIndicator(
              //     borderSide: BorderSide(color: Colors.red, width: 2.0)
              // ),
              onTap: (index) {
                // 这里数据在生命周期里初始化

                // _tabController.animateTo(index);
                _selectedTabIndex = index;
                if (index == 1) {
                  return;
                }
                // setState(() {
                //   if (index == 0) {
                //     _loading = true;
                //   } else {
                //     _loading2 = true;
                //   }
                // });
                if (index == 0) {
                  _loading = true;
                } else {
                  _loading2 = true;
                }
                data0 = [];
                data1 = [];
                Future.wait([
                  PackageDao.listWithColumnType({
                    "types": typeMap[index]!.join(","),
                    "examId": IndustryDao.getExamKey().examId,
                    "buying": "false"
                  }).then((res) {
                    data0 = res;
                  }),
                  PackageDao.listWithColumnType({
                    "types": typeMap[index]!.join(","),
                    "examId": IndustryDao.getExamKey().examId,
                    "buying": "true"
                  }).then((res) {
                    data1 = res;
                  })
                ]).whenComplete(() {
                  setState(() {
                    if (index == 0) {
                      _loading = false;
                    } else {
                      _loading2 = false;
                    }
                  });
                });
              },
              tabs: [
                Tab(
                  child: Text("课程"),
                ),
                Tab(
                  child: Text("直播"),
                ),
                // Tab(
                //   child: Text("常见问题"),
                // ),
                Tab(
                  child: Text("资料"),
                ),
              ],
              controller: tabController,
            ),
          ),
          SizedBox(
            height: 1.sh -
                48 -
                ScreenUtil().statusBarHeight -
                ScreenHelper.bottomNavigationBarHeight -
                55,
            child: TabBarView(
              controller: tabController,
              physics: NeverScrollableScrollPhysics(),
              children: [
                if (_loading)
                  _LoadingWidget()
                else
                  Padding(
                    padding: EdgeInsets.all(16),
                    child: ListView(
                      children: [
                        Padding(
                            padding: EdgeInsets.only(top: 16, bottom: 14),
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  "好课推荐",
                                  style: TextStyle(
                                      fontSize: 18,
                                      letterSpacing: 0.4,
                                      color: Color(0xFF21242D),
                                      fontWeight: FontWeight.w500),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    Navigator.pushNamed(context, "/video-list");
                                  },
                                  child: Text(
                                    "前往试看",
                                    style: TextStyle(color: Colors.blue),
                                  ),
                                )
                                // 某些视频是免费的
                              ],
                            )),
                        if (data0.isNotEmpty)
                          for (var item in data0)
                            Container(
                              margin: EdgeInsets.only(bottom: 10),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 6),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                spacing: 10,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  ClipRRect(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6)),
                                    child: Image.asset("images/test/2.jpg",
                                        width: 70, height: 90),
                                  ),
                                  Container(
                                    width: 1.sw - 150,
                                    child: Column(
                                      mainAxisSize: MainAxisSize.max,
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      spacing: 8,
                                      children: [
                                        Text(
                                          (item
                                              as Map<String, dynamic>)["name"],
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF21242D),
                                              fontSize: 16,
                                              fontWeight: FontWeight.w400),
                                        ),
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            Expanded(
                                              child: Row(
                                                spacing: 6,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.end,
                                                children: [
                                                  if ((item)["remark"] !=
                                                          null &&
                                                      (item)["remark"] != "")
                                                    Container(
                                                      width: 80,
                                                      child: HtmlWidget(
                                                          (item)["remark"],
                                                          textStyle: TextStyle(
                                                              color: Color(
                                                                  0xFFB2B2B2),
                                                              fontSize: 12,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis)),
                                                    ),
                                                  Text(
                                                    "￥${(item)["discountPrice"] / 100}",
                                                    style: TextStyle(
                                                        color: Colors.red,
                                                        fontSize: 14),
                                                  )
                                                ],
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                buy(
                                                    0,
                                                    PackageModel.fromJson(
                                                        item));
                                              },
                                              child: Container(
                                                padding: EdgeInsets.symmetric(
                                                    horizontal: 10,
                                                    vertical: 4),
                                                decoration: BoxDecoration(
                                                    color: Color(0xFF3C6CFF),
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(
                                                                15))),
                                                child: Text(
                                                  "立即前往",
                                                  style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: 15),
                                                ),
                                              ),
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            )
                        else
                          Container(
                            child: SvgPicture.asset("images/home/empty.svg",
                                width: 80),
                          ),
                        Padding(
                          padding: EdgeInsets.only(top: 16, bottom: 14),
                          // padding: EdgeInsets.only(top: 0, bottom: 0),
                          child: Row(
                            spacing: 10,
                            children: [
                              Text(
                                "已购科目",
                                style: TextStyle(
                                    fontSize: 18,
                                    letterSpacing: 0.4,
                                    color: Color(0xFF21242D),
                                    fontWeight: FontWeight.w500),
                              ),
                              // 提示显示的是购买全科的
                              // GestureDetector(
                              //     key: iconKey,
                              //     onTap: () {
                              //       final RenderBox button =
                              //           iconKey.currentContext!.findRenderObject()
                              //               as RenderBox;
                              //       final Offset topLeftPosition =
                              //           button.localToGlobal(Offset.zero);
                              //       final Rect rect = Rect.fromPoints(
                              //         topLeftPosition,
                              //         topLeftPosition +
                              //             button.size.bottomRight(Offset.zero),
                              //       );
                              //
                              //       showMenu(
                              //         context: context,
                              //         position: RelativeRect.fromLTRB(
                              //           rect.left,
                              //           rect.top,
                              //           ScreenUtil().screenWidth - rect.right,
                              //           ScreenUtil().screenHeight - rect.bottom,
                              //         ),
                              //         items: [
                              //           PopupMenuItem(
                              //             enabled: false,
                              //             child: Container(
                              //               padding: EdgeInsets.all(8),
                              //               decoration: BoxDecoration(
                              //                 color: Colors.white,
                              //                 borderRadius:
                              //                     BorderRadius.circular(4),
                              //                 boxShadow: [
                              //                   BoxShadow(
                              //                     color: Colors.black26,
                              //                     blurRadius: 4,
                              //                   )
                              //                 ],
                              //               ),
                              //               child: Text("显示购买全科的课程"),
                              //             ),
                              //           ),
                              //         ],
                              //       );
                              //     },
                              //     child: SvgPicture.asset(
                              //       "images/question/stem_analysis_help.svg",
                              //       width: 12,
                              //       height: 12,
                              //     ))
                            ],
                          ),
                        ),
                        if (data1.isNotEmpty)
                          for (var item in data1)
                            Container(
                              margin: EdgeInsets.only(bottom: 10),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 6),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                spacing: 10,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  ClipRRect(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6)),
                                    child: Image.asset("images/test/2.jpg",
                                        width: 70, height: 90),
                                  ),
                                  Container(
                                    width: 1.sw - 150,
                                    child: Column(
                                      mainAxisSize: MainAxisSize.max,
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      spacing: 8,
                                      children: [
                                        Text(
                                          (item
                                              as Map<String, dynamic>)["name"],
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF21242D),
                                              fontSize: 16,
                                              fontWeight: FontWeight.w400),
                                        ),
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            Container(
                                              width: 175,
                                              child: Row(
                                                spacing: 6,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.end,
                                                children: [
                                                  if ((item)["remark"] !=
                                                          null &&
                                                      (item)["remark"] != "")
                                                    Container(
                                                      width: 80,
                                                      child: HtmlWidget(
                                                          (item)["remark"],
                                                          textStyle: TextStyle(
                                                              color: Color(
                                                                  0xFFB2B2B2),
                                                              fontSize: 12,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis)),
                                                    ),
                                                ],
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                Navigator.pushNamed(
                                                    context, "/mine/course");
                                              },
                                              child: Container(
                                                padding: EdgeInsets.symmetric(
                                                    horizontal: 10,
                                                    vertical: 4),
                                                decoration: BoxDecoration(
                                                    color: Color(0xFF3C6CFF),
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(
                                                                15))),
                                                child: Text(
                                                  "前往",
                                                  style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: 15),
                                                ),
                                              ),
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            )
                      ],
                    ),
                  ),
                if (_loading1)
                  _LoadingWidget()
                else
                  // 显示日历与已预约课程
                  Padding(
                    padding: EdgeInsets.all(16),
                    child: ListView(
                      children: [
                        TableCalendar(
                          headerStyle: HeaderStyle(
                            formatButtonVisible: false, // 隐藏格式按钮
                            titleCentered: true,
                          ),
                          locale: 'zh_CN',
                          firstDay: DateTime.now(),
                          lastDay: DateTime.utc(
                            DateTime.now().year + 1,
                            DateTime.now().month + 1,
                            28,
                          ),
                          focusedDay: DateTime.now(),
                          calendarFormat: _calendarFormat,
                          eventLoader: _getEventsForDay,
                          calendarBuilders: CalendarBuilders(
                            // singleMarkerBuilder: (context, day, event) {
                            //
                            //   return Container(
                            //     decoration: BoxDecoration(
                            //       shape: BoxShape.circle,
                            //       color: Color(0xFF3C6CFF),
                            //     ),
                            //     child: Center(
                            //       child: Text(
                            //         day.day.toString(),
                            //         style: TextStyle(color: Colors.white),
                            //       ),
                            //     ),
                            //   );
                            // },
                            markerBuilder: (context, day, events) {
                              if (events.length > 0) {
                                return AnimatedContainer(
                                  margin: EdgeInsets.all(5),
                                  duration: const Duration(milliseconds: 300),
                                  decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Color(0x4fff0000)
                                      // color: events[0].color.withOpacity(0.5),
                                      ),
                                  child: Center(
                                      // child: Text(
                                      //  day.day.toString(),
                                      //   style: TextStyle(color: Colors.red),
                                      // ),
                                      ),
                                );
                                // return Positioned(
                                //   top: 1,
                                //   right: 1,
                                //   bottom: 1,
                                //   left: 1,
                                //   child: AnimatedContainer(
                                //     duration: const Duration(milliseconds: 300),
                                //     decoration: BoxDecoration(
                                //         shape: BoxShape.circle, color: Color(0x4fff0000)
                                //       // color: events[0].color.withOpacity(0.5),
                                //     ),
                                //     child: Center(
                                //       // child: Text(
                                //       //  day.day.toString(),
                                //       //   style: TextStyle(color: Colors.red),
                                //       // ),
                                //     ),
                                //   ),
                                // );
                              }
                              return null;
                            },
                            // dowBuilder: (context, day) {
                            //   if (day.weekday == DateTime.sunday) {
                            //     final text = DateFormat.E().format(day);
                            //
                            //     return Center(
                            //       child: Text(
                            //         text,
                            //         style: TextStyle(color: Colors.red),
                            //       ),
                            //     );
                            //   }
                            // },

                            // singleMarkerBuilder: (context, date, events) {
                            //   debugPrint("9999999999999"+date.toString());
                            //   if (date == DateTime.now()) {
                            //
                            //     return Container(
                            //       decoration: BoxDecoration(
                            //         shape: BoxShape.circle,
                            //         color: Colors.red, // 标注颜色
                            //       ),
                            //       child: Center(
                            //         child: Text(
                            //           date.day.toString(),
                            //           style: TextStyle(color: Colors.white),
                            //         ),
                            //       ),
                            //     );
                            //   }
                            //   return null; // 其他日期不标注
                            // },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 16, bottom: 14),
                          child: Text(
                            "预约课程",
                            style: TextStyle(
                                fontSize: 18,
                                letterSpacing: 0.4,
                                color: Color(0xFF21242D),
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                        Column(
                          spacing: 20,
                          children: [
                            if (liveList.isNotEmpty)
                              for (var item in liveList)
                                Container(
                                  height: 150,
                                  padding: EdgeInsets.all(8),
                                  decoration: ShapeDecoration(
                                    image: DecorationImage(
                                      image: AssetImage(
                                          "images/home/teacher_background.png"),
                                      fit: BoxFit.fill,
                                    ),
                                    shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(4)),
                                  ),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      spacing: 16,
                                      children: [
                                        Image.asset("images/test/1.png"),
                                        Expanded(
                                            child: Container(
                                          // width: cardWidth,
                                          padding: EdgeInsets.all(8),
                                          decoration: ShapeDecoration(
                                            color: Color(0xFFF3FAFF),
                                            shape: RoundedRectangleBorder(
                                              borderRadius: BorderRadius.only(
                                                bottomLeft: Radius.circular(4),
                                                bottomRight: Radius.circular(4),
                                              ),
                                            ),
                                          ),
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            mainAxisSize: MainAxisSize.max,
                                            children: [
                                              SizedBox(
                                                // width: 152,
                                                child: Text.rich(
                                                  TextSpan(
                                                    children: [
                                                      TextSpan(
                                                        text: '免费',
                                                        style: TextStyle(
                                                          color:
                                                              Color(0xFF6CC683),
                                                          fontSize: 14,
                                                          fontFamily:
                                                              'PingFang SC',
                                                          fontWeight:
                                                              FontWeight.w400,
                                                          height: 1,
                                                          letterSpacing: 0.28,
                                                        ),
                                                      ),
                                                      TextSpan(
                                                        text: item["title"],
                                                        style: TextStyle(
                                                          color:
                                                              Color(0xFF21242D),
                                                          fontSize: 14,
                                                          fontFamily:
                                                              'PingFang SC',
                                                          fontWeight:
                                                              FontWeight.w400,
                                                          height: 1,
                                                          letterSpacing: 0.28,
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                              Text(
                                                "${item["liveDate"]!}",
                                                style: TextStyle(
                                                  fontSize: 12,
                                                  color: Color(0xFF5C5C5C),
                                                ),
                                              ),
                                              Text(
                                                "${item["startTime"]}-${item["endTime"]}",
                                                style: TextStyle(
                                                  fontSize: 12,
                                                  color: Color(0xFF5C5C5C),
                                                ),
                                              ),
                                              Container(
                                                child: Row(
                                                  mainAxisSize:
                                                      MainAxisSize.max,
                                                  mainAxisAlignment:
                                                      MainAxisAlignment
                                                          .spaceBetween,
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.center,
                                                  children: [
                                                    Text(
                                                      '${item["appointmentNum"]}人预约',
                                                      style: TextStyle(
                                                        color:
                                                            Color(0xFF5C5C5C),
                                                        fontSize: 11,
                                                        fontFamily:
                                                            'Microsoft YaHei UI',
                                                        fontWeight:
                                                            FontWeight.w400,
                                                      ),
                                                    ),
                                                    // 已结束的不可预约
                                                    GestureDetector(
                                                      onTap: () async {
                                                        dynamic res =
                                                            await LiveDao
                                                                .haveAppoint(
                                                                    liveId: item[
                                                                        'id']!);
                                                        if (res == true) {
                                                          ToastUtil.show(
                                                              context: context,
                                                              msg:
                                                                  "您已经预约,无需重复预约");
                                                          return;
                                                        } else {
                                                          dynamic res1 =
                                                              await LiveDao
                                                                  .appoint(item[
                                                                      'id']!);
                                                          if (res1 == true) {
                                                            ToastUtil.show(
                                                                context:
                                                                    context,
                                                                msg: "预约成功");
                                                          } else {
                                                            ToastUtil.show(
                                                                context:
                                                                    context,
                                                                msg: "预约失败");
                                                          }
                                                        }
                                                      },
                                                      child: Container(
                                                        width: 54,
                                                        height: 22,
                                                        padding:
                                                            const EdgeInsets
                                                                .symmetric(
                                                                horizontal: 10,
                                                                vertical: 2),
                                                        decoration:
                                                            ShapeDecoration(
                                                          color:
                                                              Color(0xFF3C6CFF),
                                                          shape:
                                                              RoundedRectangleBorder(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        90),
                                                          ),
                                                        ),
                                                        alignment:
                                                            Alignment.center,
                                                        child: Text(
                                                          '预约',
                                                          style: TextStyle(
                                                            color: Colors.white,
                                                            fontSize: 12,
                                                            fontWeight:
                                                                FontWeight.w400,
                                                            letterSpacing: 0.12,
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        ))
                                      ]),
                                ),
                          ],
                        )
                      ],
                    ),
                  ),

                // Padding(
                //   padding: EdgeInsets.all(16),
                //   child: ListView(
                //     children: [
                //       if (questionList.isNotEmpty)
                //         for (var index=0;index<questionList.length;index++ )
                //           Container(
                //             margin:
                //                 EdgeInsets.only(top: 12, left: 16, right: 16),
                //             decoration: BoxDecoration(
                //                 color: Colors.white,
                //                 borderRadius: BorderRadius.circular(8)),
                //             // child: Container(),
                //
                //             child: ExpansionTile(
                //               title: Text(questionList[index].name!),
                //               // expandedAlignment: Alignment.centerLeft,
                //               // clipBehavior: Clip.none,
                //               // childrenPadding: EdgeInsets.only(left: 32),
                //               // collapsedShape: null,
                //               shape: RoundedRectangleBorder(
                //                 borderRadius: BorderRadius.circular(0),
                //                 side: BorderSide(
                //                     color: Colors.transparent), // 设置透明边框
                //               ),
                //               // shape: null,
                //               children: [
                //                 // Container(
                //                 //   width: double.infinity,
                //                 //   padding: EdgeInsets.all(16),
                //                 //   child: Text(
                //                 //     item.answer ?? '',
                //                 //     style: TextStyle(
                //                 //       fontSize: 14,
                //                 //       color: Color(0xFF5C5C5C),
                //                 //     ),
                //                 //   ),
                //                 // )
                //                 Text(questionList[index].answer!),
                //               ],
                //             ),
                //           )
                //     ],
                //   ),
                // ),
                if (_loading2)
                  _LoadingWidget()
                else
                  Padding(
                    padding: EdgeInsets.all(16),
                    child: ListView(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(top: 16, bottom: 14),
                          child: Text(
                            "资料推荐",
                            style: TextStyle(
                                fontSize: 18,
                                letterSpacing: 0.4,
                                color: Color(0xFF21242D),
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                        if (data0.isNotEmpty)
                          for (var item in data0)
                            Container(
                              margin: EdgeInsets.only(bottom: 10),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 6),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                spacing: 10,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  ClipRRect(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6)),
                                    child: Image.asset("images/test/2.jpg",
                                        width: 70, height: 90),
                                  ),
                                  Container(
                                    width: 1.sw - 150,
                                    child: Column(
                                      mainAxisSize: MainAxisSize.max,
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      spacing: 8,
                                      children: [
                                        Text(
                                          (item
                                              as Map<String, dynamic>)["name"],
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF21242D),
                                              fontSize: 16,
                                              fontWeight: FontWeight.w400),
                                        ),
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            Expanded(
                                              child: Row(
                                                spacing: 6,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.end,
                                                children: [
                                                  if ((item)["remark"] !=
                                                          null &&
                                                      (item)["remark"] != "")
                                                    Container(
                                                      width: 80,
                                                      child: HtmlWidget(
                                                          (item)["remark"],
                                                          textStyle: TextStyle(
                                                              color: Color(
                                                                  0xFFB2B2B2),
                                                              fontSize: 12,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis)),
                                                    ),

                                                  // Text(
                                                  //   (item)["remark"],
                                                  //   style: TextStyle(
                                                  //       color:
                                                  //       Color(0xFFB2B2B2),
                                                  //       fontSize: 12),
                                                  // ),
                                                  Text(
                                                    "￥${(item)["discountPrice"] / 100}",
                                                    style: TextStyle(
                                                        color: Colors.red,
                                                        fontSize: 14),
                                                  )
                                                ],
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                buy(
                                                    0,
                                                    PackageModel.fromJson(
                                                        item));
                                              },
                                              child: Container(
                                                padding: EdgeInsets.symmetric(
                                                    horizontal: 10,
                                                    vertical: 4),
                                                decoration: BoxDecoration(
                                                    color: Color(0xFF3C6CFF),
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(
                                                                15))),
                                                child: Text(
                                                  "立即前往",
                                                  style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: 15),
                                                ),
                                              ),
                                            )
                                          ],
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            )
                        else
                          Container(
                            child: SvgPicture.asset("images/home/empty.svg",
                                width: 80),
                          ),
                        Padding(
                          padding: EdgeInsets.only(top: 16, bottom: 14),
                          child: Text(
                            "已购资料",
                            style: TextStyle(
                                fontSize: 18,
                                letterSpacing: 0.4,
                                color: Color(0xFF21242D),
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                        if (data1.isNotEmpty)
                          for (var item in data1)
                            Container(
                              margin: EdgeInsets.only(bottom: 10),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 6),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                spacing: 10,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  ClipRRect(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6)),
                                    child: Image.asset("images/test/2.jpg",
                                        width: 70, height: 90),
                                  ),
                                  Container(
                                    width: 1.sw - 150,
                                    child: Column(
                                      mainAxisSize: MainAxisSize.max,
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      spacing: 8,
                                      children: [
                                        Text(
                                          (item
                                              as Map<String, dynamic>)["name"],
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF21242D),
                                              fontSize: 16,
                                              fontWeight: FontWeight.w400),
                                        ),
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            Container(
                                              width: 175,
                                              child: Row(
                                                spacing: 6,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.end,
                                                children: [
                                                  if ((item)["remark"] !=
                                                          null &&
                                                      (item)["remark"] != "")
                                                    Container(
                                                      width: 80,
                                                      child: HtmlWidget(
                                                          (item)["remark"],
                                                          textStyle: TextStyle(
                                                              color: Color(
                                                                  0xFFB2B2B2),
                                                              fontSize: 12,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis)),
                                                    ),
                                                ],
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: () {
                                                Navigator.pushNamed(
                                                    context, "/mine/resource");
                                              },
                                              child: Container(
                                                padding: EdgeInsets.symmetric(
                                                    horizontal: 10,
                                                    vertical: 4),
                                                decoration: BoxDecoration(
                                                    color: Color(0xFF3C6CFF),
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(
                                                                15))),
                                                child: Text(
                                                  "前往",
                                                  style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: 15),
                                                ),
                                              ),
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            )
                      ],
                    ),
                  ),
              ],
            ),
          )
        ],
      ),
    );
  }

  void buy(int index, PackageModel package) {
    () async {
      bool flag = await MyDao.versionCurrentIos();

      if (mounted) {
        showModalBottomSheet(
          context: context,
          // 设置底部弹出框全屏显示
          isScrollControlled: true,
          // 自定义弹出层高度
          constraints:
              BoxConstraints(maxHeight: ScreenUtil().screenHeight * 0.8),
          // 自定义圆角
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(24),
              topRight: Radius.circular(24),
            ),
          ),
          builder: (BuildContext context) {
            return BuyDialog(
              package: package,
              index: index,
              payHide: flag,
            );
          },
        );
      }
    }();
  }

  List<String?> _getEventsForDay(DateTime day) {
    if (liveList.isEmpty) {
      return [];
    }
    if (liveList.any((e) {
      return isSameDay(DateTime.parse(e["liveDate"]), day);
    })) {
      return ["title"];
    }
    return [];
  }

  @override
  //   wantKeepAlive
  bool get wantKeepAlive => true;

  Widget _LoadingWidget() {
    return SpinKitThreeBounce(
      color: Colors.blue,
      size: 40.0,
    );
  }
}

class GradientUnderlineTabIndicator extends Decoration {
  final List<Color> colors;
  final double lineHeight;
  final BorderRadius borderRadius;

  const GradientUnderlineTabIndicator({
    this.colors = const [Colors.blue, Colors.purple],
    this.lineHeight = 4.0,
    this.borderRadius = BorderRadius.zero,
  });

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _GradientUnderlinePainter(
        colors: colors,
        lineHeight: lineHeight,
        borderRadius: borderRadius,
        onChanged: onChanged);
  }
}

class _GradientUnderlinePainter extends BoxPainter {
  final List<Color> colors;
  final double lineHeight;
  final BorderRadius borderRadius;
  final VoidCallback? onChanged;

  _GradientUnderlinePainter({
    required this.colors,
    required this.lineHeight,
    required this.borderRadius,
    this.onChanged,
  });

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    if (configuration.size == null) return;

    final Rect rect = offset & configuration.size!;
    final Rect lineRect = Rect.fromLTWH(
      rect.left,
      rect.bottom - lineHeight,
      rect.width,
      lineHeight,
    );

    final radius = borderRadius.topLeft.y;

    final Paint paint = Paint();
    final gradient = ui.Gradient.linear(
      lineRect.topLeft,
      lineRect.topRight,
      colors,
    );
    paint.shader = gradient;

    final RRect rRect =
        RRect.fromRectAndRadius(lineRect, Radius.circular(radius));
    canvas.drawRRect(rRect, paint);
  }
}

// class DashedRectShape extends ShapeBorder {
//   final double strokeWidth;
//   final List<double> dashPattern;
//   final Color color;
//
//   DashedRectShape({
//     this.strokeWidth = 1.0,
//     this.dashPattern = const <double>[5.0, 5.0],
//     this.color = Colors.black,
//   });
//
//   @override
//   EdgeInsetsGeometry get dimensions => EdgeInsets.all(strokeWidth);
//
//   @override
//   Path getInnerPath(Rect rect, {TextDirection? textDirection}) {
//     return Path()
//       ..addRect(Rect.fromLTWH(
//         rect.left + strokeWidth / 2,
//         rect.top + strokeWidth / 2,
//         rect.width - strokeWidth,
//         rect.height - strokeWidth,
//       ));
//   }
//
//   @override
//   Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
//     return Path()
//       ..addRect(Rect.fromLTWH(
//         rect.left,
//         rect.top,
//         rect.width,
//         rect.height,
//       ));
//   }
//
//   @override
//   void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {
//     final Paint paint = Paint()
//       ..color = color
//       ..strokeWidth = strokeWidth
//       ..style = PaintingStyle.stroke;
//
//     final Path path = Path();
//
//     double x = rect.left;
//     double y = rect.top;
//     double width = rect.width;
//     double height = rect.height;
//
//     // ❗只绘制下边框虚线
//     _drawDashedLine(
//       path,
//       Offset(x, y + height), // 起点：左下角
//       Offset(x + width * 2, y + height), // 终点：右下角
//       dashPattern,
//     );
//
//     canvas.drawPath(path, paint);
//   }
//
//   void _drawDashedLine(
//       Path path, Offset start, Offset end, List<double> dashPattern) {
//     final double distance = (end - start).distance;
//     final int dashCount = (distance / (dashPattern[0] + dashPattern[1])).ceil();
//     final Offset delta = (end - start) / distance;
//
//     bool draw = true;
//     double currentDistance = 0.0;
//
//     for (int i = 0; i < dashCount; i++) {
//       final Offset segmentStart = start + delta * currentDistance;
//       final double length = dashPattern[draw ? 0 : 1];
//       final Offset segmentEnd = start + delta * (currentDistance + length);
//
//       if (draw) {
//         path.moveTo(segmentStart.dx, segmentStart.dy);
//         path.lineTo(segmentEnd.dx, segmentEnd.dy);
//       }
//
//       currentDistance += length;
//       draw = !draw;
//     }
//   }
//
//   @override
//   ShapeBorder scale(double t) => this;
// }
